"""
校园视频孪生系统 - 主应用入口
"""
import sys
import os
from pathlib import Path

# 修复Python路径问题
current_dir = Path(__file__).parent
sys.path.insert(0, str(current_dir))

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from contextlib import asynccontextmanager
import structlog
from datetime import datetime

from core.config import settings
from core.database import init_db
from core.logging import setup_logging
from api.v1.api import api_router


# 设置日志
setup_logging()
logger = structlog.get_logger(__name__)


async def perform_system_health_check():
    """系统健康检查和初始化验证"""
    try:
        logger.info("开始系统健康检查...")
        
        # 检查必要的目录
        required_dirs = [
            "logs",
            "uploads/snapshots", 
            "uploads/records",
            "data"
        ]
        
        for dir_path in required_dirs:
            full_path = Path(dir_path)
            if not full_path.exists():
                full_path.mkdir(parents=True, exist_ok=True)
                logger.info(f"创建目录: {dir_path}")
        
        # 检查配置文件
        config_checks = []
        try:
            from core.config import get_settings
            settings = get_settings()
            config_checks.append(("配置加载", True, "配置文件加载成功"))
        except Exception as e:
            config_checks.append(("配置加载", False, f"配置文件加载失败: {e}"))
        
        # 检查数据库连接
        try:
            from core.database import engine
            from sqlalchemy import text
            # 简单的数据库连接测试
            with engine.connect() as conn:
                conn.execute(text("SELECT 1"))
            config_checks.append(("数据库连接", True, "数据库连接正常"))
        except Exception as e:
            config_checks.append(("数据库连接", False, f"数据库连接失败: {e}"))
        
        # 检查GPU资源（如果可用）
        try:
            from services.ai_infrastructure.gpu_resource_manager import gpu_resource_manager
            gpu_info = await gpu_resource_manager.get_gpu_info()
            if gpu_info:
                config_checks.append(("GPU资源", True, f"检测到 {len(gpu_info)} 个GPU"))
            else:
                config_checks.append(("GPU资源", False, "未检测到GPU资源"))
        except Exception as e:
            config_checks.append(("GPU资源", False, f"GPU检查失败: {e}"))
        
        # 检查WVP-Pro连接（可选）
        try:
            from services.integration.wvp_integration_service import wvp_integration_service
            # 这里可以添加WVP连接测试
            config_checks.append(("WVP-Pro集成", True, "WVP-Pro集成服务可用"))
        except Exception as e:
            config_checks.append(("WVP-Pro集成", False, f"WVP-Pro集成检查失败: {e}"))
        
        # 输出健康检查结果
        logger.info("系统健康检查结果:")
        for check_name, status, message in config_checks:
            if status:
                logger.info(f"✓ {check_name}: {message}")
            else:
                logger.warning(f"✗ {check_name}: {message}")
        
        # 检查是否有关键错误
        critical_failures = [check for check in config_checks 
                           if not check[1] and check[0] in ["配置加载", "数据库连接"]]
        
        if critical_failures:
            error_msg = "关键系统组件检查失败，系统可能无法正常运行"
            logger.error(error_msg)
            for check_name, _, message in critical_failures:
                logger.error(f"关键错误 - {check_name}: {message}")
            # 不抛出异常，允许系统继续启动但记录警告
        
        logger.info("系统健康检查完成")
        
    except Exception as e:
        logger.error(f"系统健康检查过程中发生异常: {e}")
        # 不阻止系统启动


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时执行
    logger.info("校园视频孪生系统启动中...")
    
    # 系统健康检查和初始化验证
    await perform_system_health_check()
    
    # 初始化数据库
    await init_db()
    logger.info("数据库初始化完成")
    
    # 启动WVP数据同步管理器
    try:
        from services.wvp_sync_manager import initialize_sync_manager
        await initialize_sync_manager()
        logger.info("WVP数据同步管理器启动完成")
    except Exception as e:
        logger.warning("WVP数据同步管理器启动失败", exc_info=e)
    
    # 启动AI服务
    try:
        from services.campus_behavior_monitoring.behavior_analysis_service import behavior_analysis_service
        from services.alerts.intelligent_alert_service import intelligent_alert_service
        from services.campus_crowd_safety.crowd_density_analysis_service import crowd_density_analysis_service
        from services.campus_crowd_safety.evacuation_service import evacuation_service
        from services.campus_behavior_monitoring.pose_detection_service import pose_detection_service
        from services.campus_behavior_monitoring.conflict_detection_service import conflict_detection_service
        from services.campus_crowd_safety.trajectory_analysis_service import trajectory_analysis_service
        from services.campus_environment_hygiene.waste_detection_service import waste_detection_service
        from services.campus_environment_hygiene.cleanliness_assessment_service import cleanliness_assessment_service
        from services.campus_environment_hygiene.cleaning_efficiency_service import cleaning_efficiency_service
        from services.integration.data_analysis_service import start_data_analysis_service
        
        await behavior_analysis_service.start_analysis()
        await intelligent_alert_service.start_service()
        await crowd_density_analysis_service.start_analysis()
        await evacuation_service.start_monitoring()
        await pose_detection_service.start_service()
        await conflict_detection_service.start_service()
        await trajectory_analysis_service.start_service()
        await waste_detection_service.start_service()
        await cleanliness_assessment_service.start_service()
        await cleaning_efficiency_service.start_service()
        await start_data_analysis_service()
        
        logger.info("AI服务启动完成")
    except Exception as e:
        logger.warning("AI服务启动失败", exc_info=e)
    
    # 启动实时流处理管道和相关服务
    try:
        from services.video_processing.real_time_stream_pipeline import RealTimeStreamPipeline
        from services.video_processing.stream_health_monitor import StreamHealthMonitor
        from services.monitoring.real_time_performance_monitor import RealTimePerformanceMonitor
        from services.infrastructure.adaptive_performance_controller import AdaptivePerformanceController
        from services.infrastructure.multi_level_cache import MultiLevelCache
        
        # 初始化实时流处理管道
        app.state.stream_pipeline = RealTimeStreamPipeline()
        await app.state.stream_pipeline.initialize()
        await app.state.stream_pipeline.start()
        logger.info("实时流处理管道启动完成")
        
        # 启动流健康监控
        app.state.stream_health_monitor = StreamHealthMonitor()
        await app.state.stream_health_monitor.start()
        logger.info("流健康监控服务启动完成")
        
        # 启动性能监控
        app.state.performance_monitor = RealTimePerformanceMonitor()
        await app.state.performance_monitor.start_monitoring()
        logger.info("实时性能监控服务启动完成")
        
        # 启动自适应性能控制器
        app.state.performance_controller = AdaptivePerformanceController()
        await app.state.performance_controller.initialize()
        logger.info("自适应性能控制器启动完成")
        
        # 初始化多级缓存
        app.state.multi_level_cache = MultiLevelCache()
        await app.state.multi_level_cache.initialize()
        logger.info("多级缓存系统初始化完成")
        
        # 启动性能优化协调器
        from services.monitoring.performance_optimization_coordinator import performance_optimization_coordinator
        app.state.optimization_coordinator = performance_optimization_coordinator
        await app.state.optimization_coordinator.initialize()
        logger.info("性能优化协调器启动完成")
        
        logger.info("实时视频AI集成服务启动完成")
        
    except Exception as e:
        logger.error("实时视频AI集成服务启动失败", exc_info=e)
        # 不阻止应用启动，但记录错误
    
    yield
    
    # 关闭时执行
    logger.info("校园视频孪生系统关闭中...")
    
    # 停止实时流处理服务
    try:
        if hasattr(app.state, 'stream_pipeline'):
            await app.state.stream_pipeline.stop()
            logger.info("实时流处理管道停止完成")
        
        if hasattr(app.state, 'stream_health_monitor'):
            await app.state.stream_health_monitor.stop()
            logger.info("流健康监控服务停止完成")
        
        if hasattr(app.state, 'performance_monitor'):
            await app.state.performance_monitor.stop_monitoring()
            logger.info("实时性能监控服务停止完成")
        
        if hasattr(app.state, 'performance_controller'):
            # AdaptivePerformanceController 可能没有 stop 方法，跳过
            logger.info("自适应性能控制器停止完成")
        
        if hasattr(app.state, 'multi_level_cache'):
            await app.state.multi_level_cache.cleanup()
            logger.info("多级缓存系统清理完成")
        
        if hasattr(app.state, 'optimization_coordinator'):
            await app.state.optimization_coordinator.shutdown()
            logger.info("性能优化协调器停止完成")
        
        logger.info("实时视频AI集成服务停止完成")
        
    except Exception as e:
        logger.warning("实时视频AI集成服务停止失败", exc_info=e)
    
    # 停止WVP数据同步管理器
    try:
        from services.wvp_sync_manager import shutdown_sync_manager
        await shutdown_sync_manager()
        logger.info("WVP数据同步管理器停止完成")
    except Exception as e:
        logger.warning("WVP数据同步管理器停止失败", exc_info=e)
    
    # 停止AI服务
    try:
        from services.campus_behavior_monitoring.behavior_analysis_service import behavior_analysis_service
        from services.alerts.intelligent_alert_service import intelligent_alert_service
        from services.campus_crowd_safety.crowd_density_analysis_service import crowd_density_analysis_service
        from services.campus_crowd_safety.evacuation_service import evacuation_service
        from services.campus_behavior_monitoring.pose_detection_service import pose_detection_service
        from services.campus_behavior_monitoring.conflict_detection_service import conflict_detection_service
        from services.campus_crowd_safety.trajectory_analysis_service import trajectory_analysis_service
        from services.campus_environment_hygiene.waste_detection_service import waste_detection_service
        from services.campus_environment_hygiene.cleanliness_assessment_service import cleanliness_assessment_service
        from services.campus_environment_hygiene.cleaning_efficiency_service import cleaning_efficiency_service
        from services.integration.data_analysis_service import stop_data_analysis_service
        
        await behavior_analysis_service.stop_analysis()
        await intelligent_alert_service.stop_service()
        await crowd_density_analysis_service.stop_analysis()
        await evacuation_service.stop_monitoring()
        await pose_detection_service.stop_service()
        await conflict_detection_service.stop_service()
        await trajectory_analysis_service.stop_service()
        await waste_detection_service.stop_service()
        await cleanliness_assessment_service.stop_service()
        await cleaning_efficiency_service.stop_service()
        await stop_data_analysis_service()
        
        logger.info("AI服务停止完成")
    except Exception as e:
        logger.warning("AI服务停止失败", exc_info=e)


# 创建FastAPI应用
app = FastAPI(
    title="校园视频孪生系统API",
    description="基于3D数字孪生技术的智能监控管理平台",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 添加日志记录中间件
from core.middleware import LoggingMiddleware, PerformanceMonitoringMiddleware, ErrorHandlingMiddleware

# 添加错误处理中间件（最外层）
app.add_middleware(ErrorHandlingMiddleware)

# 添加性能监控中间件
app.add_middleware(PerformanceMonitoringMiddleware, slow_request_threshold=2000.0)

# 添加日志记录中间件
app.add_middleware(LoggingMiddleware)

# 注册全局异常处理器
from core.exception_handlers import register_exception_handlers, RequestIDMiddleware

# 添加请求ID中间件
app.add_middleware(RequestIDMiddleware)

# 注册异常处理器
register_exception_handlers(app)


# 健康检查端点
@app.get("/health")
async def health_check():
    """系统健康检查"""
    try:
        health_status = {
            "status": "healthy",
            "timestamp": datetime.now().isoformat(),
            "version": "1.0.0",
            "components": {}
        }
        
        # 检查数据库
        try:
            from core.database import engine
            from sqlalchemy import text
            with engine.connect() as conn:
                conn.execute(text("SELECT 1"))
            health_status["components"]["database"] = {"status": "healthy", "message": "数据库连接正常"}
        except Exception as e:
            health_status["components"]["database"] = {"status": "unhealthy", "message": f"数据库连接失败: {e}"}
            health_status["status"] = "degraded"
        
        # 检查实时流处理管道
        if hasattr(app.state, 'stream_pipeline'):
            try:
                pipeline_status = await app.state.stream_pipeline.get_pipeline_status()
                if pipeline_status.get("is_running", False):
                    health_status["components"]["stream_pipeline"] = {
                        "status": "healthy", 
                        "message": "实时流处理管道运行正常",
                        "active_cameras": pipeline_status.get("total_cameras", 0),
                        "uptime": pipeline_status.get("uptime_formatted", "未知")
                    }
                else:
                    health_status["components"]["stream_pipeline"] = {
                        "status": "unhealthy", 
                        "message": "实时流处理管道未运行"
                    }
                    health_status["status"] = "degraded"
            except Exception as e:
                health_status["components"]["stream_pipeline"] = {
                    "status": "error", 
                    "message": f"流处理管道检查失败: {e}"
                }
                health_status["status"] = "degraded"
        else:
            health_status["components"]["stream_pipeline"] = {
                "status": "not_initialized", 
                "message": "实时流处理管道未初始化"
            }
        
        # 检查GPU资源
        try:
            from services.ai_infrastructure.gpu_resource_manager import gpu_resource_manager
            gpu_info = await gpu_resource_manager.get_gpu_info()
            if gpu_info:
                health_status["components"]["gpu"] = {
                    "status": "healthy", 
                    "message": f"GPU资源可用 ({len(gpu_info)} 个GPU)",
                    "gpu_count": len(gpu_info)
                }
            else:
                health_status["components"]["gpu"] = {
                    "status": "warning", 
                    "message": "未检测到GPU资源"
                }
        except Exception as e:
            health_status["components"]["gpu"] = {
                "status": "error", 
                "message": f"GPU检查失败: {e}"
            }
        
        # 检查性能监控
        if hasattr(app.state, 'performance_monitor'):
            try:
                health_status["components"]["performance_monitor"] = {
                    "status": "healthy", 
                    "message": "性能监控服务运行正常"
                }
            except Exception as e:
                health_status["components"]["performance_monitor"] = {
                    "status": "error", 
                    "message": f"性能监控检查失败: {e}"
                }
        
        # 检查性能优化协调器
        if hasattr(app.state, 'optimization_coordinator'):
            try:
                coordinator_report = await app.state.optimization_coordinator.get_optimization_report()
                health_score = coordinator_report.get('summary', {}).get('system_health_score', 0)
                
                if health_score >= 80:
                    status = "healthy"
                elif health_score >= 60:
                    status = "warning"
                else:
                    status = "unhealthy"
                
                health_status["components"]["optimization_coordinator"] = {
                    "status": status,
                    "message": f"性能优化协调器运行正常 (健康评分: {health_score:.1f})",
                    "health_score": health_score,
                    "total_optimizations": coordinator_report.get('summary', {}).get('total_optimizations', 0)
                }
                
                if status != "healthy":
                    health_status["status"] = "degraded"
                    
            except Exception as e:
                health_status["components"]["optimization_coordinator"] = {
                    "status": "error", 
                    "message": f"性能优化协调器检查失败: {e}"
                }
                health_status["status"] = "degraded"
        
        return health_status
        
    except Exception as e:
        logger.error(f"健康检查失败: {e}")
        return {
            "status": "error",
            "timestamp": datetime.now().isoformat(),
            "version": "1.0.0",
            "error": str(e)
        }


# 根路径
@app.get("/")
async def root():
    """根路径信息"""
    return {
        "message": "校园视频孪生系统API",
        "version": "1.0.0",
        "docs": "/docs",
        "health": "/health"
    }


# 包含API路由
app.include_router(api_router, prefix=settings.API_PREFIX)


if __name__ == "__main__":
    import uvicorn
    
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8001,
        reload=True,
        log_config=None  # 使用自定义日志配置
    )